﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;

namespace Dynamic_UI_Framework
{
    public abstract class AdapterMappingBase<K, T>
        where T : class
        where K : class
    {
        public AdapterMappingBase(string name)
        {
            this.Name = name;
        }

        public string Name { get; set; }

        private readonly Dictionary<K, T> mappings = new Dictionary<K, T>();

        public Dictionary<K, T> Mappings
        {
            get { return mappings; }
        }

        public virtual void RegisterMapping(K controlType, T adapter)
        {
            if (controlType == null)
            {
                throw new ArgumentNullException("controlType");
            }

            if (adapter == null)
            {
                throw new ArgumentNullException("adapter");
            }

            if (mappings.ContainsKey(controlType))
            {
                throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture,
                                                                  "已经存在"));
            }

            mappings.Add(controlType, adapter);
        }

        public T GetMapping(K controlType)
        {
            K currentType = controlType;

            //while (currentType != null)
            {
                if (mappings.ContainsKey(currentType))
                {
                    return mappings[currentType];
                }

                //currentType = currentType.BaseType;
            }
            throw new KeyNotFoundException("映射没有注册");
        }

        public T GetMappingByTypeFullName(string typeFullName)
        {
            if (typeof(K).FullName.Equals(typeof(Type).FullName) == false)
                return null;

            foreach (var item in mappings)
            {
                if ((item.Key as Type).FullName.Equals(typeFullName))
                    return item.Value as T;
            }
            return null;
        }
    }
}
